<template>
    <div class="session-docx-parser">
        <!-- 1. 文件上传区域 - 修复了拖拽状态问题 -->
        <div class="upload-area" @dragover.prevent="handleDragOver" @dragleave.prevent="handleDragLeave"
            @drop.prevent="handleFileDrop" @dragenter.prevent>
            <div class="drag-overlay" v-if="isDragging"></div>

            <label class="upload-label">
                选择“.docx”文件：
                <input type="file" accept=".docx" @change="handleFileSelect" class="file-input"
                    :disabled="isProcessing" />
            </label>
            &nbsp;&nbsp;

            <button class="parse-btn"
                @click="open('https://admin.hqx.com.cn/Public/App/image/%E7%94%B5%E8%84%91%E7%AB%AF%E9%A3%9E%E4%B9%A6%E5%AF%BC%E5%87%BAword%E6%95%99%E7%A8%8B.pdf')">
                电脑飞书教程
            </button>
            &nbsp;
            <button class="parse-btn"
                @click="open('https://admin.hqx.com.cn/Public/App/image/%E6%89%8B%E6%9C%BA%E9%A3%9E%E4%B9%A6%E5%AF%BC%E5%87%BAword%E6%95%99%E7%A8%8B.pdf')">
                手机飞书教程
            </button>


            <!-- 清空按钮 -->
            <button class="reset-btn" @click="resetToInitialState" :disabled="!file && formattedSessions.length === 0">
                清空
            </button>

            <p class="file-info" v-if="file">{{ `已选择：${file.name}（大小：${(file.size / 1024).toFixed(2)}KB）` }}</p>

            <!-- 拖拽提示 -->
            <p class="drag-hint" v-if="!file">或拖拽.docx文件到此处上传</p>
        </div>

        <!-- 2. 核心操作区（筛选+按钮） -->
        <div class="main-controls" v-if="formattedSessions.length > 0">
            <!-- 昵称筛选下拉框 -->
            <select class="nickname-filter" v-model="activeNickname" @change="onFilterChange">
                <option value="">全部内容</option>
                <option v-for="nickname in uniqueNicknames" :key="nickname" :value="nickname">
                    {{ nickname }}
                </option>
            </select>

            <!-- 全选/反选按钮 -->
            <button class="select-all-btn" @click="checkAll">
                全选
            </button>
            <button class="select-all-btn" @click="invertSelection">
                反选
            </button>

            <!-- 提取选中内容（复制） -->
            <button class="copy-btn" @click="copySelectedContent" :disabled="!hasSelected || isProcessing">
                提取选中内容（复制）
            </button>
        </div>

        <!-- 3. 结果展示区域 -->
        <div class="result-area" v-if="formattedSessions.length > 0">
            <h4>
                提取结果（
                总：{{ formattedSessions.length }}条，
                筛选后：{{ filteredSessions.length }}条，
                选中：{{ selectedCount }}条
                ）：
            </h4>
            <div class="content-container">
                <!-- 单个会话项 -->
                <div v-for="(session, index) in filteredSessions" :key="index" class="session-item">
                    <input type="checkbox" class="session-checkbox" v-model="session.checked"
                        @change="updateSelectedCount">
                    <div class="session-content">
                        <div class="session-header">
                            <span class="nickname">{{ session.nickname }}</span>
                            <span class="datetime">{{ session.date }} {{ session.time }}</span>
                        </div>
                        <div class="session-text">{{ session.content }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 4. 状态提示 -->
        <div class="status" :class="statusType">{{ statusText }}</div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import mammoth from 'mammoth';

// 响应式变量
const file = ref(null);
const formattedSessions = ref([]); // 所有会话（含checked状态）
const activeNickname = ref(''); // 当前筛选的昵称（空表示全部）
const isProcessing = ref(false);
const statusText = ref('');
const statusType = ref('');
const isDragging = ref(false); // 用于拖拽状态的标识
const dragCounter = ref(0); // 用于跟踪拖拽进入/离开的计数器

// 计算属性
const uniqueNicknames = computed(() => {
    return [...new Set(formattedSessions.value.map(s => s.nickname))];
});

const filteredSessions = computed(() => {
    if (!activeNickname.value) return formattedSessions.value;
    return formattedSessions.value.filter(s => s.nickname === activeNickname.value);
});

const isAllSelected = computed(() => {
    return filteredSessions.value.length > 0
        && filteredSessions.value.every(s => s.checked);
});

const selectedCount = computed(() => {
    return filteredSessions.value.filter(s => s.checked).length;
});

const hasSelected = computed(() => {
    return selectedCount.value > 0;
});

const selectedContent = computed(() => {
    return filteredSessions.value.filter(s => s.checked);
});

// 方法
const handleFileSelect = (e) => {
    const selectedFile = e.target.files[0];
    if (!selectedFile) return;
    processFile(selectedFile);
};

const handleDragOver = () => {
    if (!isDragging.value) {
        isDragging.value = true;
    }
};

const handleDragLeave = (e) => {
    // 检查鼠标是否真的离开上传区域
    const rect = e.currentTarget.getBoundingClientRect();
    const isOutside = (
        e.clientY < rect.top ||
        e.clientY > rect.bottom ||
        e.clientX < rect.left ||
        e.clientX > rect.right
    );

    if (isOutside) {
        isDragging.value = false;
    }
};

const handleFileDrop = (e) => {
    isDragging.value = false;
    const droppedFile = e.dataTransfer.files[0];
    if (!droppedFile) return;
    processFile(droppedFile);
};

const processFile = (selectedFile) => {
    if (!selectedFile.name.endsWith('.docx')) {
        setStatus('请选择.docx格式的文件', 'error');
        file.value = null;
        return;
    }

    file.value = selectedFile;
    activeNickname.value = ''; // 重置筛选
    formattedSessions.value = [];
    setStatus(`已选中文件：${selectedFile.name}`, 'success');
    parseFile();
};

const parseFile = async () => {
    if (!file.value) return;

    isProcessing.value = true;
    setStatus('正在解析文件内容...', 'success');

    try {
        const buffer = await fileToBuffer(file.value);
        const result = await mammoth.extractRawText({ arrayBuffer: buffer });
        const sessions = formatSessions(result.value);

        // 为每条会话添加checked属性（默认全选）
        formattedSessions.value = sessions.map(s => ({ ...s, checked: true }));

        if (formattedSessions.value.length === 0) {
            setStatus('未提取到有效会话内容', 'error');
            return;
        }

        setStatus(`成功提取${formattedSessions.value.length}条会话，可筛选后操作`, 'success');
    } catch (error) {
        setStatus(`解析失败：${error.message}`, 'error');
        console.error('解析错误：', error);
    } finally {
        isProcessing.value = false;
    }
};

const onFilterChange = () => {
    const filterText = activeNickname.value || '全部昵称';
    setStatus(`已筛选：${filterText}（共${filteredSessions.value.length}条）`, 'success');
};

const checkAll = () => {
    filteredSessions.value.forEach(session => {
        session.checked = true;
    });
    updateSelectedCount();
};

const invertSelection = () => {
    filteredSessions.value.forEach(session => {
        session.checked = !session.checked;
    });
    updateSelectedCount();
};

const updateSelectedCount = () => {
    // 空操作，仅触发computed更新
};

const copySelectedContent = async () => {
    try {
        // 仅提取content，用单个\n分隔
        const text = selectedContent.value
            .map(s => {
                if (activeNickname.value) {
                    return s.content
                } else {
                    return s.nickname + "：" + s.content
                }
            })
            .join('\n');

        await navigator.clipboard.writeText(text);
        setStatus(`已复制${selectedCount.value}条内容到剪贴板`, 'success');
    } catch (error) {
        setStatus('复制失败，请重试', 'error');
        console.error('复制错误：', error);
    }
};

const resetToInitialState = () => {
    // 重置文件输入
    const fileInput = document.querySelector('.file-input');
    if (fileInput) {
        fileInput.value = '';
    }

    // 重置所有状态
    file.value = null;
    formattedSessions.value = [];
    activeNickname.value = '';
    statusText.value = '';
    statusType.value = '';
    isDragging.value = false;
};

const fileToBuffer = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject(new Error('文件读取失败'));
        reader.readAsArrayBuffer(file);
    });
};

const formatSessions = (rawText) => {
    if (!rawText) return [];

    const lines = rawText.split('\n').filter(line => line.trim());
    const sessions = [];
    const reg = /(\d{4}年\d{1,2}月\d{1,2}日) (\d{2}:\d{2})/;

    lines.forEach(line => {
        const match = line.trim().match(reg);
        if (!match) return;

        const [fullMatch, date, time] = match;
        const nickname = line.substring(0, line.indexOf(fullMatch)).trim();
        const content = line.substring(line.indexOf(fullMatch) + fullMatch.length).trim();

        sessions.push({ nickname, date, time, content });
    });

    return sessions;
};

const setStatus = (text, type) => {
    statusText.value = text;
    statusType.value = type;
};

const open = (href) => {
    window.open(href, '_blank');
};
</script>

<style scoped>
/* 样式部分保持不变 */
.session-docx-parser {
    padding: 20px;
    max-width: 1000px;
    margin: 0 auto;
    font-family: 'Segoe UI', system-ui, sans-serif;
}

/* 上传区域样式 - 增加拖拽相关样式 */
.upload-area {
    margin-bottom: 20px;
    padding: 20px;
    border: 2px dashed #ccc;
    border-radius: 6px;
    position: relative;
    transition: border-color 0.3s;
}

.upload-area:hover {
    border-color: #42b983;
}

/* 拖拽覆盖层 */
.drag-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(66, 185, 131, 0.1);
    border-radius: 4px;
    z-index: 1;
}

.drag-hint {
    margin-top: 10px;
    color: #999;
    font-size: 13px;
    font-style: italic;
}

.upload-label {
    display: inline-block;
    padding: 8px 16px;
    background: #42b983;
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
    position: relative;
    z-index: 2;
}

.upload-label:hover {
    background: #359568;
}

.file-input {
    display: none;
}

.file-info {
    margin-top: 10px;
    color: #666;
    font-size: 14px;
    position: relative;
    z-index: 2;
}

/* 清空按钮样式 */
.reset-btn {
    padding: 8px 16px;
    background: #e74c3c;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: background 0.3s;
    margin-left: 10px;
    position: relative;
    z-index: 2;
}

.reset-btn:disabled {
    background: #ecb8b8;
    cursor: not-allowed;
}

.reset-btn:hover:not(:disabled) {
    background: #c0392b;
}

/* 核心控制区样式 */
.main-controls {
    margin: 15px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
}

/* 筛选下拉框 */
.nickname-filter {
    padding: 6px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 13px;
    background: #fff;
    cursor: pointer;
}

/* 按钮样式 */
.select-all-btn {
    padding: 6px 12px;
    background: #f39c12;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    transition: background 0.3s;
}

.select-all-btn:hover {
    background: #e67e22;
}

.copy-btn {
    padding: 6px 12px;
    background: #3498db;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    transition: background 0.3s;
}

.copy-btn:disabled {
    background: #bdc3c7;
    cursor: not-allowed;
}

.copy-btn:hover:not(:disabled) {
    background: #2980b9;
}

/* 解析按钮 */
.parse-btn {
    padding: 8px 16px;
    background: #42b983;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: background 0.3s;
    position: relative;
    z-index: 2;
}

.parse-btn:disabled {
    background: #bdc3c7;
    cursor: not-allowed;
}

.parse-btn:hover:not(:disabled) {
    background: #359568;
}

/* 结果展示区域 */
.result-area {
    margin-top: 15px;
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.result-area h4 {
    margin: 0 0 12px;
    color: #333;
    font-size: 16px;
}

.content-container {
    padding: 12px;
    background: #f8f9fa;
    border-radius: 4px;
    max-height: 400px;
    overflow-y: auto;
    line-height: 1.5;
}

/* 单个会话项 */
.session-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px dashed #e1e1e1;
}

.session-item:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

/* 复选框 */
.session-checkbox {
    margin: 2px 10px 0 0;
    width: 16px;
    height: 16px;
    cursor: pointer;
}

/* 会话内容 */
.session-content {
    flex: 1;
}

.session-header {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
}

.nickname {
    color: #2c3e50;
    font-weight: 500;
    font-size: 14px;
}

.datetime {
    margin-left: 12px;
    color: #999;
    font-size: 12px;
}

.session-text {
    color: #34495e;
    font-size: 14px;
}

/* 状态提示 */
.status {
    margin-top: 15px;
    padding: 8px;
    border-radius: 4px;
    font-size: 14px;
    transition: all 0.3s;
}

.status.success {
    color: #27ae60;
    background: #ecf9f2;
    border: 1px solid #d5f0e3;
}

.status.error {
    color: #e74c3c;
    background: #fef2f2;
    border: 1px solid #fcdada;
}
</style>
